<script>
import { ref, defineComponent, onMounted } from "vue";
import axios from "axios";

export default defineComponent({
  setup() {
    const swiperList = ref([]);
    const showModalRef = ref(false);
    const previewImageUrlRef = ref("");

    function remove({ file, fileList }) {
      // console.log("删除", file);
      // console.log("删除", fileList);
      swiperList.value = fileList.filter((item) => {
        return item.id !== file.id;
      });
    }

    function handlePreview(file) {
      const { url } = file;
      previewImageUrlRef.value = url;
      showModalRef.value = true;
    }

    function handleFile({ file, event }) {
      file.url = JSON.parse(event.target.response).data;
      file._type = "new";
      swiperList.value.push(file);
    }

    function save() {
      axios({
        method: "post",
        url: "/homeSwiper/batchSave",
        data: swiperList.value.map((tempItem) => ({
          ...tempItem,
          id: tempItem._type === "new" ? "" : tempItem.id,
        })),
      }).then(function (response) {
        if (response.data.code === 200) {
          window.$message.success("保存成功");
        }
      });
    }

    onMounted(() => {
      axios({
        method: "post",
        url: "/homeSwiper/findList",
        data: {},
      }).then(function (response) {
        if (response.data.code === 200) {
          response.data.data.forEach((element) => {
            element.status = "finished";
          });
          swiperList.value.push(...response.data.data);
        }
      });
    });

    return {
      swiperList,
      remove,
      handlePreview,
      handleFile,
      save,
      showModal: showModalRef,
      previewImageUrl: previewImageUrlRef,
    };
  },
});
</script>

<template>
  <n-upload
    class="uploadStyle"
    action="/api/cosFile/upload"
    :default-file-list="swiperList"
    list-type="image-card"
    @preview="handlePreview"
    :on-finish="handleFile"
    :on-remove="remove"
  />
  <n-modal v-model:show="showModal" preset="card" style="width: 600px">
    <img :src="previewImageUrl" style="width: 100%" />
  </n-modal>

  <n-button type="primary" @click="save" class="btnStyle"> 保存 </n-button>
</template>

<style>
.uploadStyle {
  margin: 20px;
}

.btnStyle {
  margin-left: 20px;
}
</style>
